package com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_main

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.ViewModelProvider
import com.anythink.core.api.ATAdInfo
import com.anythink.interstitial.api.ATInterstitial
import com.bp.hearthealth.pulse.lnapps.BpApplication
import com.bp.hearthealth.pulse.lnapps.R
import com.bp.hearthealth.pulse.lnapps.ads.admob.banner_ad.AdMobBannerAdManager
import com.bp.hearthealth.pulse.lnapps.ads.admob.interstitial_ad.AdMobInterstitialAdManager
import com.bp.hearthealth.pulse.lnapps.ads.admob.native_ad.AdMobNativeAdManager
import com.bp.hearthealth.pulse.lnapps.ads.admob.rewarded_ad.AdMobRewardedAdManager
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsSwitch
import com.bp.hearthealth.pulse.lnapps.ads.timer.AppTimer
import com.bp.hearthealth.pulse.lnapps.ads.topon.banner_ad.TopOnBannerAdListener
import com.bp.hearthealth.pulse.lnapps.ads.topon.banner_ad.TopOnBannerAdManager
import com.bp.hearthealth.pulse.lnapps.ads.topon.interstitial_ad.TopOnInterAdManager
import com.bp.hearthealth.pulse.lnapps.ads.topon.native_ad.TopOnNativeAdManager
import com.bp.hearthealth.pulse.lnapps.ads.topon.open_ad.TopOnOpenAdManager
import com.bp.hearthealth.pulse.lnapps.ads.topon.open_ad.observer.SplashType
import com.bp.hearthealth.pulse.lnapps.ads.topon.open_ad.observer.TopOnSplashFinishObservable
import com.bp.hearthealth.pulse.lnapps.ads.topon.open_ad.observer.TopOnSplashFinishObserver
import com.bp.hearthealth.pulse.lnapps.base.BpBaseActivity
import com.bp.hearthealth.pulse.lnapps.base.bp_liveDataBus.BpLiveDataBus
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_extension.UIHelperBp
import com.bp.hearthealth.pulse.lnapps.bp_extension.clearToast
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_heart.bp_detect.BpHeartRateActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_language_gender.bp_gender.BpGenderActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_language_gender.bp_splash.BpSplashActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_dialog.BpGuideCamareDialog
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_dialog.QuitDialog
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_home.BpHomeFragment
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_lifestyle.bp_fragment.BpLifeStyleFragment
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_me.BpMeFragment
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_tracker.tracker.BpTrackerFragment
import com.bp.hearthealth.pulse.lnapps.bp_utils.BPActivityCollector
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.bp.hearthealth.pulse.lnapps.bp_utils.DoubleClickListener
import com.bp.hearthealth.pulse.lnapps.databinding.ActivityMainBgBinding
import com.bp.hearthealth.pulse.lnapps.notification.NotificationService
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import java.util.Timer
import java.util.TimerTask
import kotlin.*


class BpMainActivity : BpBaseActivity<ActivityMainBgBinding>(), TopOnSplashFinishObserver {

    private lateinit var adMobBannerAdManager: AdMobBannerAdManager
    private var homeFragment: BpHomeFragment? = null
    private var trackerFragment: BpTrackerFragment? = null
    private var lifestyleFragment: BpLifeStyleFragment? = null
    private var meFragment: BpMeFragment? = null
    private val fragmentManager: FragmentManager by lazy { supportFragmentManager }
    private lateinit var mMainViewModel: BpMainViewModel
    private var quitDialog: QuitDialog? = null
    private var toponBannerManager: TopOnBannerAdManager? = null
    private var guide = false

    private var ids = mutableListOf(
        R.id.navigation_health,
        R.id.navigation_tracker,
        R.id.navigation_heart,
        R.id.navigation_lifestyle,
        R.id.navigation_me
    ).toMutableList()

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        jumpFragment(intent)
    }

    private fun jumpFragment(intent: Intent?) {
        val extras = intent?.extras
        if (extras != null) {
            BpLiveDataBus.with<Int>(Constants.SWITCH_FRAGMENT)
                .postData(extras.getInt("notification", 0))
        } else {
            //点击通知栏跳转首页进入后,跳转LifeStyle
            if (Constants.LIFE_STYLE_JUMP) {
                Constants.LIFE_STYLE_JUMP = false
                BpLiveDataBus.with<Int>(Constants.SWITCH_FRAGMENT).postData(2)
            } else {
                BpLiveDataBus.with<Int>(Constants.SWITCH_FRAGMENT).postData(0)
            }
        }
    }

    private fun initTopOnInterAd() {
        TopOnInterAdManager.releaseManualLoadInterstitialAd()
        if (BPActivityCollector.isActivityDestroy(BpSplashActivity::class.java) && BPActivityCollector.isActivityDestroy(
                BpGenderActivity::class.java
            )
        ) {
            LogUtil.iTopOn("BpMainActivity 加载插页广告")
            TopOnInterAdManager.initManualLoadInterstitialAd(this)
            TopOnInterAdManager.manualLoadAd()
        } else {
            Timer().schedule(object : TimerTask() {
                override fun run() {
                    LogUtil.iTopOn("BpMainActivity 延迟加载插页广告")
                    TopOnInterAdManager.initManualLoadInterstitialAd(this@BpMainActivity)
                    TopOnInterAdManager.manualLoadAd()
                }
            }, 1000)
        }
    }

    override fun onResume() {
        super.onResume()
        if (toponBannerManager ==null) {
            toponBannerManager = TopOnBannerAdManager()
            toponBannerManager!!.initBannerView(this)
        }
        if (guide) {
            loadTopOnBannerAd()
        }
        guide = true
    }

    override fun initData() {
        super.initData()
        TopOnSplashFinishObservable.registerSplash(this)
//        TopOnOpenAdManager.initTopOnSplashAd()

        initTopOnInterAd()
        //底部banner广告

//        loadAdMobBannerAd()

        checkNotificationPermission()
        LogUtil.i("BpMainActivity initData ")
        binding.lifecycleOwner = this
        binding.tvHeartRate.setOnClickListener(object : DoubleClickListener() {
            override fun onNoDoubleClick(v: View?) {
                LogUtil.i("点击tvHeartRate ")
                BpLiveDataBus.with<Boolean>(Constants.CHECK_PERMISSWION).postData(true)
            }
        })
        if (permissionLiveData.hasActiveObservers()) {
            permissionLiveData.observe(this) { permission ->
                hasPermission = permission
                if (permission) {
                    startActivity(Intent(this, BpHeartRateActivity::class.java))
                    LogUtil.i("savedInstanceState == null   permission: $permission")
                }
            }
        }
        BpLiveDataBus.with<Boolean>(AdsSwitch.adAppControl).observe(this) {
            binding.bannerAdContainer.visibility = View.GONE
        }
        BpLiveDataBus.with<Int>(Constants.SWITCH_FRAGMENT).observe(this) {
            LogUtil.i("显示LifeStyle")
            when (it) {
                0 -> {
                    binding.navView.selectedItemId = R.id.navigation_health
                }

                1 -> {
                    binding.navView.selectedItemId = R.id.navigation_tracker
                }

                else -> {
                    binding.navView.selectedItemId = R.id.navigation_lifestyle
                }
            }
            switchFragment(it)
        }
        initViewModel()
        initBottomNavigation()
        clearToast(binding.navView, ids)
        jumpFragment(intent)
    }

    private fun loadTopOnBannerAd() {
        if (toponBannerManager?.getBannerView() != null) {
            toponBannerManager?.setBannerListener(object : TopOnBannerAdListener {
                override fun onBannerShow(entity: ATAdInfo) {
                    ATInterstitial.entryAdScenario(Constants.TOP_ON_NATIVE_ID, "f664723428019e")
                    LogUtil.iTopOn("TopOn 配置的场景ID为: 【Health页_横幅广告】")
                }

                override fun onBannerLoaded() {
                    setTopOnBannerView()
                }
            })
            if (toponBannerManager?.getBannerView()?.checkAdStatus()?.isReady == true) {
                setTopOnBannerView()
            } else {
                if (toponBannerManager?.getBannerView()?.checkAdStatus()?.isLoading != true) {
                    toponBannerManager?.getBannerView()?.loadAd()
                }
            }
        }
    }

    private fun setTopOnBannerView() {
        binding.bannerAdContainer.visibility = View.VISIBLE
        binding.bannerAdContainer.removeAllViews()
        binding.bannerAdContainer.addView(
            toponBannerManager?.getBannerView(),
            FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                binding.bannerAdContainer.layoutParams.height
            )
        )
    }

    private fun checkNotificationPermission() {
        if (XXPermissions.isGranted(this, Permission.POST_NOTIFICATIONS)) {
            startNotificationService()
        } else {
            requestNotificationPermission()
        }
    }

    private fun requestNotificationPermission() {
        XXPermissions.with(this).permission(Permission.POST_NOTIFICATIONS)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: List<String>, allGranted: Boolean) {
                    startNotificationService()
                }

                override fun onDenied(permissions: List<String>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {
                        val permissionDialog = BpGuideCamareDialog(activity!!)
                        permissionDialog.showDialog(UIHelperBp.getString(R.string._dialog_notification_permission_str))
                        permissionDialog.setOnBtnClickLisener(object :
                            BpGuideCamareDialog.OnBtnClickListener {
                            override fun onBtnClick() {
                                XXPermissions.startPermissionActivity(
                                    activity!!, permissions
                                )
                            }
                        })
                    }
                }
            })
    }

    private fun startNotificationService() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(Intent(BpApplication.context, NotificationService::class.java))
        } else {
            startService(Intent(BpApplication.context, NotificationService::class.java))
        }
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
        initBottomNavigation()
    }

    private fun initViewModel() {
        mMainViewModel = ViewModelProvider(this)[BpMainViewModel::class.java]
        mMainViewModel.getCurrentName().observe(this) { index ->
            switchFragment(index)
        }
    }

    private fun initBottomNavigation() {
        //去掉底部默认选中背景
        try {
            binding.navView.run {
                itemIconTintList = null
                setOnNavigationItemSelectedListener {
                    when (it.itemId) {
                        R.id.navigation_health -> saveAndSwitch(0)
                        R.id.navigation_tracker -> saveAndSwitch(1)
                        R.id.navigation_lifestyle -> saveAndSwitch(2)
                        R.id.navigation_me -> saveAndSwitch(3)
                    }
                    true
                }
            }
        } catch (e: Exception) {
            finish()
        }

    }

    private fun saveAndSwitch(index: Int) {
        mMainViewModel.saveSelect(index)
        switchFragment(index)
    }

    private fun switchFragment(index: Int) {
        fragmentManager.beginTransaction().apply {
            hideFragments(this)
            when (index) {
                0 -> {
                    if (homeFragment == null) {
                        homeFragment = BpHomeFragment()
                        add(R.id.homeActivityFragContainer, homeFragment!!)
                    } else {
                        show(homeFragment!!)
                    }
                }

                1 -> {
                    if (trackerFragment == null) {
                        trackerFragment = BpTrackerFragment()
                        add(R.id.homeActivityFragContainer, trackerFragment!!)
                    } else {
                        show(trackerFragment!!)
                    }
                }

                2 -> {
                    if (lifestyleFragment == null) {
                        lifestyleFragment = BpLifeStyleFragment()
                        add(R.id.homeActivityFragContainer, lifestyleFragment!!)
                    } else {
                        show(lifestyleFragment!!)
                    }
                }

                3 -> {
                    if (meFragment == null) {
                        meFragment = BpMeFragment()
                        add(R.id.homeActivityFragContainer, meFragment!!)
                    } else {
                        show(meFragment!!)
                    }
                }
            }
        }.commit()//commitAllowingStateLoss
    }


    //隐藏所有的Fragment
    private fun hideFragments(transaction: FragmentTransaction) {
        homeFragment?.let { transaction.hide(it) }
        trackerFragment?.let { transaction.hide(it) }
        lifestyleFragment?.let { transaction.hide(it) }
        meFragment?.let { transaction.hide(it) }
    }

    @Deprecated("Deprecated in Java", ReplaceWith("finish()"))
    override fun onBackPressed() {
        showQuitDialog()
//        finish()
    }

//    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
//        if (keyCode ==KeyEvent.KEYCODE_BACK) {
//            showQuitDialog()
//        }
//        return super.onKeyDown(keyCode, event)
//    }

    private fun showQuitDialog() {
        if (quitDialog == null) {
            quitDialog = QuitDialog(activity!!)
        }
        quitDialog!!.showDialog()
        quitDialog!!.setOnBtnClickLisener(object : QuitDialog.OnBtnClickListener {
            override fun onBtnClick() {
//                moveTaskToBack(true)
//                TopOnSplashFinishObservable.notifySplash(SplashType.TYPE_LAUNCH_FINISH)
                finish()
            }
        })
    }


    /**
     * ● 导航栏下，横幅广告
     *     ○ 横幅广告资源加载到，展示广告
     *     ○ 横幅广告资源未加载到，隐藏广告位
     */
    private fun loadAdMobBannerAd() {
        if (!this::adMobBannerAdManager.isInitialized) {
            adMobBannerAdManager = AdMobBannerAdManager(
                this, this, Constants.Adaptive_Banner, binding.bannerAdContainer
            )
        }
        adMobBannerAdManager.loadBannerAd()
    }

    override fun onDestroy() {
        if (_binding != null) {
            binding.bannerAdContainer.removeView(toponBannerManager?.getBannerView())
            binding.bannerAdContainer.removeAllViews()
        }
        super.onDestroy()
        toponBannerManager?.setBannerListener(null)
        toponBannerManager?.releaseBannerAd(true)
        toponBannerManager = null
//        releaseAdmob()
        releaseTopOn()
        AppTimer.stop()
    }

    private fun releaseTopOn() {
        TopOnOpenAdManager.releaseOpenAd()
        TopOnInterAdManager.releaseManualLoadInterstitialAd()
        TopOnNativeAdManager.release()
    }

    private fun releaseAdmob() {
        AdMobNativeAdManager.release()
        AdMobRewardedAdManager.release()
        AdMobInterstitialAdManager.release()
    }

    override fun topOnSplashFinish(splashType: SplashType) {
        //MainActivity未销毁时，加载

    }


}